package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityOrderRepayBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.presenter.OrderRepayPresenter
import com.shipwe.loans.ui.view.IOrderRepayView
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.UserPointsHelper
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/26 17:14
 * @Annotation：订单还款页
 */
class ActivityOrderRepay: ShipweActivity(), IOrderRepayView {
    lateinit var binding: ActivityOrderRepayBinding
    var presenter: OrderRepayPresenter? = null

    companion object {
        private const val INTENT_KEY_TITLE = "title"
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pTitle: String,pName: String, pToken: String) {
            val intent = Intent(context, ActivityOrderRepay::class.java)
            intent.putExtra(INTENT_KEY_TITLE, pTitle)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun getShipweRootView(): View? {
        binding = ActivityOrderRepayBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.VISIBLE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle(getProductTitle())

        initOrderRepayRefreshView()
        binding.repayContent.visibility = View.GONE

        //积分抵扣金额
        binding.repayOffsetAmount.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.repayOffsetAmount.paint.isAntiAlias = true//抗锯齿
        //原始还款金额
        binding.repayOriginalPrice.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG//删除线
        binding.repayOriginalPrice.paint.isAntiAlias = true//抗锯齿
    }

    @SuppressLint("SetTextI18n")
    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("${getProductName()} Repay Page",getProductName(),getProductToken())
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"${getProductName()} Repay Page")
        }
        //提示
        binding.repayDiscountTips.setOnClickListener {
            val discountRate = BigDecimal(CustomConfigsHelper.getShipweDiscountRate()).multiply(BigDecimal("100")).stripTrailingZeros().toPlainString()
            showErrorTipsDialog(String.format(getString(R.string.repay_details_points_max_tips),"$discountRate%"))
        }
        //切换是否使用积分抵扣
        binding.repayUsePointSwitch.setOnCheckedChangeListener { _, isChecked ->
            onOrderRepayCheckUsePointsDiscount()
        }
        //pay
        binding.repayConfirm.setOnClickListener {
            showShipweLoading()
            presenter?.loadOrderPayLinkAction()
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOAN_REPAY,"${getProductName()} Repay")
        }
    }

    override fun initShipweData() {
        presenter = OrderRepayPresenter(this)

        showShipweLoading()
        presenter?.loadOrderRepayInfoAction()
    }

    /* 初始化刷新 */
    private fun initOrderRepayRefreshView() {
        //禁止加载
        binding.orderRepayRefreshView.setEnableLoadMore(false)
        binding.orderRepayRefreshView.setEnableAutoLoadMore(false)
        binding.orderRepayRefreshView.setOnRefreshListener {
            presenter?.loadOrderRepayInfoAction()
        }
        binding.orderRepayRefreshView.setOnLoadMoreListener {
            binding.orderRepayRefreshView.finishLoadMore()
        }
    }

    /**
     * 获取查看的产品名称
     */
    private fun getProductTitle(): String {
        return intent.extras!!.getString(INTENT_KEY_TITLE).toString()
    }

    override fun getProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    override fun getProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    @SuppressLint("SetTextI18n")
    override fun showOrderRepayInfo(data: JSONObject) {
        binding.repayContent.visibility = View.VISIBLE

        //单位
        val unit = data.optString("currency")
        val overdueDay = data.optString("overdueDay")

        binding.repayOriginalPrice.text = "${presenter?.repayInfo?.optString("repayAmount")} $unit"
        binding.repayDueDate.text = data.optString("repayDate")
        binding.repayFundAmount.text = "${data.optString("amount")} $unit"
        binding.repayInterest.text = "${data.optString("interest")} $unit"
        binding.repayServiceFee.text = "${data.optString("serviceFee")} $unit"
        binding.repayOverdueDays.text = String.format(getString(R.string.loan_apply_days),overdueDay)
        binding.repayOverduePenalty.text = "${data.optString("overdueAmount")} $unit"

        //已逾期
        if(overdueDay.toInt() > 0){
            binding.repayStatus.text = String.format(getString(R.string.repay_days_overdue),overdueDay)
            binding.repayStatus.setTextColor(Color.parseColor("#FFEC273A"))
            binding.repayOverdueDays.setTextColor(Color.parseColor("#FFEC273A"))
        } else {
            binding.repayStatus.text = String.format(getString(R.string.repay_days_left),data.optString("remainRepayDay"))
            binding.repayStatus.setTextColor(Color.parseColor("#FFFF8D08"))
            binding.repayOverdueDays.setTextColor(Color.parseColor("#FF222222"))
        }
        onOrderRepayCheckUsePointsDiscount()

        val showPoints = String.format(getString(R.string.repay_have_points_key),data.optString("score"))
        val showDiscountAmount = "${BigDecimal(data.optString("score")).multiply(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).stripTrailingZeros().toInt()} $unit"
        val showText = String.format(getString(R.string.repay_details_receive_points),showPoints,showDiscountAmount)
        val showIndex = showText.indexOf(showPoints)
        val showIndexAmount = showText.indexOf(showDiscountAmount)
        val spString = SpannableString(showText)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFEC273A")), showIndex, showIndex + showPoints.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(UnderlineSpan(), showIndex, showIndex + showPoints.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FFEC273A")), showIndexAmount, showIndexAmount + showDiscountAmount.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(UnderlineSpan(), showIndexAmount, showIndexAmount + showDiscountAmount.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.repayReceivePoints.text = spString
    }

    /**
     * 跳转还款链接
     */
    override fun showOrderPayLink(linkUrl: String) {
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * PIN流程，进入订单状态查询
     */
    override fun showOrderPaymentStatusPage(thirdOrderId: String, points: String) {
        ActivityOrderPayPin.start(this,getProductName(),getProductToken(),thirdOrderId,points)
    }

    /**
     * 切换是否使用积分
     */
    @SuppressLint("SetTextI18n")
    private fun onOrderRepayCheckUsePointsDiscount(){
        val data = presenter?.repayInfo ?: return
        binding.repayDiscountTips.visibility = View.GONE
        val unit = data.optString("currency")
        //当前积分数
        val curtPoints = BigDecimal("${UserPointsHelper.getShipweUserPoints()}")
        //所有积分可抵扣金额  乘 multiply
        val maxDiscountAmount = curtPoints.multiply(BigDecimal(CustomConfigsHelper.getShipweChangeRate()))
        //当前订单可使用积分抵扣的最大金额 = 借款金额 * 最大抵扣比例
        val curtMaxDiscountAmount = BigDecimal(data.optString("amount","0")).multiply(BigDecimal(CustomConfigsHelper.getShipweDiscountRate()))
        //可以抵消积分  除 divide
        var discountPoints = BigDecimal(maxDiscountAmount.toInt()).divide(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).toPlainString()
        //积分可抵扣的最大金额 > 当前订单可用积分抵扣的最大金额 -> 当前订单可抵扣的最大金额
        if (maxDiscountAmount > curtMaxDiscountAmount){
            discountPoints = curtMaxDiscountAmount.divide(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).stripTrailingZeros().toPlainString()
            binding.repayDiscountTips.visibility = View.VISIBLE
        }
        binding.repayPointsUse.text = String.format(getString(R.string.repay_details_points_to_offset),discountPoints)

        val discountAmount = BigDecimal(discountPoints).multiply(BigDecimal(CustomConfigsHelper.getShipweChangeRate())).stripTrailingZeros().toPlainString()
        binding.repayOffsetAmount.text = "$discountAmount $unit"
        binding.repayPointsDeduction.text = "-$discountAmount $unit"
        binding.repayPointsDeduction.setTextColor(Color.parseColor("#FFFE8833"))

        //没有积分
        if (discountPoints.toInt() == 0){
            binding.repayOriginalPrice.visibility = View.GONE
            binding.repayPointsLine.visibility = View.GONE
            binding.repayPointsDiscount.visibility = View.GONE
            binding.repayPointsUseViewGroup.visibility = View.GONE
            binding.repayTotal.text = "${data.optString("repayAmount")} $unit"
            binding.repayUsePointSwitch.isChecked = false
            presenter?.repayInfo?.put("isUsePoints",false)
        } else {
            binding.repayOriginalPrice.visibility = View.VISIBLE
            binding.repayPointsLine.visibility = View.VISIBLE
            binding.repayPointsDiscount.visibility = View.VISIBLE
            binding.repayPointsUseViewGroup.visibility = View.VISIBLE
            presenter?.repayInfo?.put("isUsePoints",binding.repayUsePointSwitch.isChecked)
            when(binding.repayUsePointSwitch.isChecked){
                true -> {
                    binding.repayOriginalPrice.visibility = View.VISIBLE
                    binding.repayTotal.text = "${BigDecimal(presenter?.repayInfo?.optString("repayAmount")).subtract(BigDecimal(discountAmount)).stripTrailingZeros().toPlainString()} $unit"
                    binding.repayPointsDeduction.text = "-$discountAmount $unit"
                    binding.repayPointsDeduction.setTextColor(Color.parseColor("#FFFE8833"))
                    presenter?.repayInfo?.put("usePoints",discountPoints)
                }
                else -> {
                    binding.repayOriginalPrice.visibility = View.GONE
                    binding.repayTotal.text = "${presenter?.repayInfo?.optString("repayAmount")} $unit"
                    binding.repayPointsDeduction.text = "-0 $unit"
                    binding.repayPointsDeduction.setTextColor(Color.parseColor("#FF222222"))
                }
            }
        }
    }

    override fun dismissShipweLoading() {
        super.dismissShipweLoading()
        binding.orderRepayRefreshView.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_REPAYMENT_START,getProductName())
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOAN_REPAYMENT_END,getProductName())
    }
}